package com.spring.activity;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.spring.gowhere.R;
import com.spring.httputils.RequestParams;
import com.spring.httputils.RestClient;
import com.spring.httputils.TextHttpResponseHandler;
import com.spring.model.ReturnAccountInfo;
import com.spring.model.XFData;
import com.spring.tool.App;
import com.spring.util.Constant;
import com.spring.util.DialogUtil;
import com.spring.widget.DialogDatePicker;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 消费明细查询
 * 
 * @author Administrator
 * 
 */
public class QueryXFListActivity extends BaseActivity {
	RestClient restClient = null;
	private PullToRefreshListView xflistview;
	MyHandler myHandler;
	ReturnAccountInfo accountinfo = null;
	String username = null;
	String logintype = null;
	List<XFData> xfdatalist = null;

	private TextView querykq, querykqendtime;
	private Button btnquery;
	private LinearLayout linearlayout01;
	String starttime;
	String endtime;
	private int mCurrentPage = 1;
	MessageAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.myxflist);
		// Intent intent = new Intent("android.intent.action.MUSIC_PLAYER");
		// startActivity(intent);
		linearlayout01 = (LinearLayout) findViewById(R.id.linearlayout01);
		querykq = (TextView) findViewById(R.id.querykq);
		querykqendtime = (TextView) findViewById(R.id.querykqendtime);
		xflistview = (PullToRefreshListView) findViewById(R.id.xflistview);
		btnquery =(Button)findViewById(R.id.btnlogin);

		
		SharedPreferences userInfo = getSharedPreferences("user_info", 0);
		username = userInfo.getString("username", "");
		logintype = userInfo.getString("logintype", "");
		ImageButton imageButton = (ImageButton) findViewById(R.id.title_left_ib);
		imageButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		TextView textView = (TextView) findViewById(R.id.title_tv);
		textView.setText("消费明细");

		Calendar c = Calendar.getInstance();
		mStartDate = c.getTime();
		mEndDate = c.getTime();
		SimpleDateFormat df = new SimpleDateFormat(
				"yyyy-MM-dd", Locale.UK);
		starttime = df.format(mStartDate);
		endtime = df.format(mEndDate);

		querykq.setText("开始时间："+starttime);
		querykqendtime.setText("结束时间："+endtime);
		querykq.setFocusable(false);
		querykqendtime.setFocusable(false);
		myHandler = new MyHandler();
		boolean islianwang = new Constant().isConnect(QueryXFListActivity.this);
			btnquery.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if(!new Constant().isConnect(QueryXFListActivity.this)){
						return;
					}

					if(mStartDate==null){
						DialogUtil.showHintDialog(QueryXFListActivity.this, "开始日期不能为空");
						return;
					}
					if(mEndDate==null){
						DialogUtil.showHintDialog(QueryXFListActivity.this,"结束日期不能为空");
						return;
					}
					int day = (int)((mEndDate.getTime()-mStartDate.getTime())/(1000*3600*24));
					if(day<0){
						DialogUtil.showHintDialog(QueryXFListActivity.this, "结束日期必须大于开始日期");
					} else if(day>30){
						DialogUtil.showHintDialog(QueryXFListActivity.this,"查询日期范围不能超过30天");
					} else {
						loadData(1);
					}

				}
			});
			querykq.setOnClickListener(new  startDtaeListener());
			querykqendtime.setOnClickListener(new endDtaeListener());
		// 下拉刷新时的提示文本设置
		xflistview.getLoadingLayoutProxy(true, false).setLastUpdatedLabel("下拉刷新");
		xflistview.getLoadingLayoutProxy(true, false).setPullLabel("");
		xflistview.getLoadingLayoutProxy(true, false).setRefreshingLabel("正在刷新");
		xflistview.getLoadingLayoutProxy(true, false).setReleaseLabel("放开以刷新");
		// 上拉加载更多时的提示文本设置
		xflistview.getLoadingLayoutProxy(false, true).setLastUpdatedLabel("上拉加载");
		xflistview.getLoadingLayoutProxy(false, true).setPullLabel("");
		xflistview.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载...");
		xflistview.getLoadingLayoutProxy(false, true).setReleaseLabel("放开以加载");
		xflistview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				if (refreshView.isHeaderShown()) {
					Log.d("", "下拉刷新... ");
					initPage();
					loadData(mCurrentPage);

				} else {
					Log.d("", "上拉加载更多... ");
					loadData(mCurrentPage);
				}
			}
		});
		xfdatalist = new ArrayList<XFData>();
		adapter = new MessageAdapter(
				QueryXFListActivity.this, xfdatalist);
		xflistview.setAdapter(adapter);
		xflistview.setMode(PullToRefreshBase.Mode.BOTH);


		}

	private void initPage(){
		mCurrentPage = 1;
	}

	private void addPage(){
		mCurrentPage ++;
	}

	private void loadData(int index) {
		restClient = new RestClient(QueryXFListActivity.this);
		String url = App.getInstance().url+"/QueryXFList";
		sendHttpDate(url,index);
	}


	private Date mStartDate;
	private Date mEndDate;

	private class startDtaeListener implements OnClickListener{

		@Override
		public void onClick(View view) {
			final Calendar cal = Calendar.getInstance();
			DialogDatePicker datePicker = new DialogDatePicker(QueryXFListActivity.this,
					new DatePickerDialog.OnDateSetListener() {

						@Override
						public void onDateSet(DatePicker view, int year,
											  int monthOfYear, int dayOfMonth) {
							cal.set(Calendar.YEAR, year);
							cal.set(Calendar.MONTH, monthOfYear);
							cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
							SimpleDateFormat df = new SimpleDateFormat(
									"yyyy-MM-dd", Locale.UK);
							mStartDate = cal.getTime();
							querykq.setText("开始时间："+df.format(cal.getTime()));
						}
					}, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
					cal.get(Calendar.DAY_OF_MONTH));
			datePicker.getDatePicker().setCalendarViewShown(false);
			Window window = datePicker.getWindow();
			window.setGravity(Gravity.CENTER);
			window.setWindowAnimations(R.style.DialogstyleLeft);
			datePicker.show();
		}
	}

	private class endDtaeListener implements OnClickListener{

		@Override
		public void onClick(View view) {
			final Calendar cal = Calendar.getInstance();
			DialogDatePicker datePicker = new DialogDatePicker(QueryXFListActivity.this,
					new DatePickerDialog.OnDateSetListener() {

						@Override
						public void onDateSet(DatePicker view, int year,
											  int monthOfYear, int dayOfMonth) {
							cal.set(Calendar.YEAR, year);
							cal.set(Calendar.MONTH, monthOfYear);
							cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
							SimpleDateFormat df = new SimpleDateFormat(
									"yyyy-MM-dd", Locale.UK);
							mEndDate = cal.getTime();
							querykqendtime.setText("结束时间：" +df.format(cal.getTime()));
						}
					}, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
					cal.get(Calendar.DAY_OF_MONTH));
			datePicker.getDatePicker().setCalendarViewShown(false);
			Window window = datePicker.getWindow();
			window.setGravity(Gravity.CENTER);
			window.setWindowAnimations(R.style.DialogstyleLeft);
			datePicker.show();
		}
	}

	/**
	 * 接受消息,处理消息 ,此Handler会与当前主线程一块运行
	 * */

	class MyHandler extends Handler {
		public MyHandler() {
		}

		public MyHandler(Looper L) {
			super(L);
		}

		// 子类必须重写此方法,接受数据
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			Log.d("MyHandler", "handleMessage......");
			super.handleMessage(msg);
			// 此处可以更新UI
			switch (msg.arg1) {
			case 1:
				if (xfdatalist != null && xfdatalist.size()>0) {
					linearlayout01.setVisibility(View.GONE);
					xflistview.setVisibility(View.VISIBLE);
					adapter.notifyDataSetChanged();
				}else{
					Toast.makeText(QueryXFListActivity.this, "没有查询到相关数据",  Toast.LENGTH_SHORT).show();
				}
				break;
			case 2:
				Toast.makeText(QueryXFListActivity.this,"无更多数据！",Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
			xflistview.onRefreshComplete();
		}
	}

	private void sendHttpDate(String url, final int index) {
		SimpleDateFormat df = new SimpleDateFormat(
				"yyyy-MM-dd", Locale.UK);
		starttime = df.format(mStartDate);
		endtime = df.format(mEndDate);
		RequestParams requestparams = new RequestParams(url, "POST");
		requestparams.put("LoginAccount", username);
		requestparams.put("LoginType", logintype);
		requestparams.put("DateStart", starttime);
		requestparams.put("DateEnd", endtime);
		requestparams.put("PageIndex", ""+index);

		TextHttpResponseHandler textHttpResponseHandler = new TextHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String responseString) {
				// TODO Auto-generated method stub
				Log.e("TAG", "responseString---" + responseString);
				try {
					AnalysisData(responseString,index);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				// TODO Auto-generated method stub
				Log.e("TAG", "responseString---" + responseString);
				try {
					AnalysisData(responseString,index);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		try {
			restClient.post(url, requestparams, textHttpResponseHandler);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * json数据解析
	 * 
	 * @param strResult
	 * @throws JSONException
	 */
	private void AnalysisData(String strResult,int index) throws JSONException {
		if(index==1)xfdatalist.clear();
		/**
		 * 这里需要分析服务器回传的json格式数据，
		 */
		if (strResult != null) {
			JSONObject jsonobject = new JSONObject(strResult);
			JSONArray jsonArray = jsonobject.getJSONArray("XFList");
			// XFlist = new ReturnXFList();
			if(jsonArray!=null&&jsonArray.length()>0){
				addPage();
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);
					XFData xfdata = new XFData();
					xfdata.setBagName(jsonObject2.getString("BagName").equals("") ? null
							: jsonObject2.getString("BagName"));
					xfdata.setConsumeDate(jsonObject2.getString("ConsumeDate")
							.equals("") ? null : jsonObject2
							.getString("ConsumeDate"));
					xfdata.setConsumeValue(jsonObject2.getDouble("ConsumeValue"));
					xfdata.setBagValue(jsonObject2.getDouble("BagValue"));
					xfdata.setAreaName(jsonObject2.getString("AreaName").equals("") ? null
							: jsonObject2.getString("AreaName"));

					xfdata.setTermName(jsonObject2.getString("TermName").equals("") ? null
							: jsonObject2.getString("TermName"));
					xfdata.setMealName(jsonObject2.getString("MealName").equals("") ? null
							: jsonObject2.getString("MealName"));
					xfdata.setAccountName(jsonObject2.getString("AccountName")
							.equals("") ? null : jsonObject2
							.getString("AccountName"));
					xfdata.setReservedField1(jsonObject2
							.getString("ReservedField1"));
					xfdata.setReservedField2(jsonObject2
							.getString("ReservedField2"));
					xfdatalist.add(xfdata);
					// XFlist.XFList.add(xfdata);
				}
			}

		}else {
			Message msg = new Message();
			msg.arg1 = 2;
			QueryXFListActivity.this.myHandler.sendMessage(msg); // 向Handler发送消息,更新UI
			return;
		}
		if(xfdatalist!=null&&xfdatalist.size()>0){
			Message msg = new Message();
			msg.arg1 = 1;
			QueryXFListActivity.this.myHandler.sendMessage(msg); // 向Handler发送消息,更新UI
		}else{
			Message msg = new Message();
			msg.arg1 = 2;
			QueryXFListActivity.this.myHandler.sendMessage(msg); // 向Handler发送消息,更新UI
		}

	}

	public class MessageAdapter extends BaseAdapter {

		private LayoutInflater mInflater;
		private List<XFData> returnInfoList;

		public MessageAdapter(Context context, List<XFData> lists) {
			this.mInflater = LayoutInflater.from(context);
			this.returnInfoList = lists;

		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			if (returnInfoList != null) {
				return returnInfoList.size();
			}
			return 0;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.xflistadapter, null);
				holder.BagName = (TextView) convertView
						.findViewById(R.id.txBagName);
				holder.ConsumeDate = (TextView) convertView
						.findViewById(R.id.txConsumeDate);
				holder.ConsumeValue = (TextView) convertView
						.findViewById(R.id.txConsumeValue);
				holder.BagValue = (TextView) convertView
						.findViewById(R.id.txBagValue);
				holder.AreaName = (TextView) convertView
						.findViewById(R.id.txAreaName);

				holder.TermName = (TextView) convertView
						.findViewById(R.id.txTermName);

				holder.MealName = (TextView) convertView
						.findViewById(R.id.txMealName);

				holder.AccountName = (TextView) convertView
						.findViewById(R.id.txAccountName);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.BagName.setText(returnInfoList.get(position).getBagName());
			holder.ConsumeDate.setText(returnInfoList.get(position)
					.getConsumeDate());
			holder.ConsumeValue.setText(returnInfoList.get(position)
					.getConsumeValue() + "");
			holder.BagValue.setText(returnInfoList.get(position).getBagValue()
					+ "");
			holder.AreaName.setText(returnInfoList.get(position).getAreaName()
					+ "");

			holder.TermName.setText(returnInfoList.get(position).getTermName());

			holder.MealName.setText(returnInfoList.get(position).getMealName());

			holder.AccountName.setText(returnInfoList.get(position)
					.getAccountName());

			return convertView;
		}

		public class ViewHolder {
			public TextView BagName;
			public TextView ConsumeDate;
			public TextView ConsumeValue;
			public TextView BagValue;
			public TextView AreaName;
			public TextView TermName;
			public TextView MealName;
			public TextView AccountName;

		}

	}
}
